<template>
    <el-dialog :visible.sync="value" fullscreen center :show-close="false">

        <template slot="title">
            <h1>{{parentData.examName}}</h1>
            <el-button v-loading.fullscreen.lock="fullscreenLoading" type="success"  @click="handleSubmit">交卷</el-button>
        </template>

        <!-- 单选题 -->
        <el-timeline  v-if="examData.singleList && examData.singleList.length > 0">
            <el-timeline-item :color="singleAskList[index] && singleAskList[index] != '5' ? '#0bbd87' : ''" :timestamp="'第' + (index + 1) + '道单选题'"  placement="top" v-for="(single,index) in examData.singleList" :key="single.id">
                <el-card shadow="never" style="border:0rem;background-color: lightgoldenrodyellow;">
                    <template slot="header">
                        <h3 style="margin:0px 0px 20px 0px;display : inline-block" v-html="single.singleContent"></h3>
                    </template>
                    <el-radio-group v-model="singleAskList[index]">
                        <el-radio label="1" style="margin:0px 0px 10px 0px">A: {{single.singleOptionA}}</el-radio><br/>
                        <el-radio label="2" style="margin:0px 0px 10px 0px">B: {{single.singleOptionB}}</el-radio><br/>
                        <el-radio label="3" style="margin:0px 0px 10px 0px">C: {{single.singleOptionC}}</el-radio><br/>
                        <el-radio label="4" style="margin:0px 0px 10px 0px">D: {{single.singleOptionD}}</el-radio><br/>
                    </el-radio-group>
                </el-card>
            </el-timeline-item>
        </el-timeline>

        <el-timeline v-if="examData.selectionList && examData.selectionList.length > 0">
            <el-timeline-item :color="checkboxAskList[index] && checkboxAskList[index].indexOf('5') == -1 ? '#0bbd87' : ''" :timestamp="'第' + (index + 1) + '道多选题'"  placement="top" v-for="(selection,index) in examData.selectionList" :key="selection.id">
                <el-card shadow="never" style="border:0rem;background-color: aliceblue">
                    <template slot="header">
                        <h3 style="margin:0px 0px 20px 0px;display : inline-block" v-html="selection.selectionContent"></h3>
                    </template>
                    <el-checkbox-group v-model="checkboxAskList[index]">
                        <el-checkbox label="1" style="margin-bottom: 5px">A. {{selection.selectionOptionA}}</el-checkbox><br>
                        <el-checkbox label="2" style="margin-bottom: 5px">B. {{selection.selectionOptionB}}</el-checkbox><br>
                        <el-checkbox label="3" style="margin-bottom: 5px">C. {{selection.selectionOptionC}}</el-checkbox><br>
                        <el-checkbox label="4" style="margin-bottom: 5px">D. {{selection.selectionOptionD}}</el-checkbox><br>
                    </el-checkbox-group>
                </el-card>
            </el-timeline-item>
        </el-timeline>


        <el-timeline v-if="examData.askList && examData.askList.length > 0">
            <el-timeline-item :timestamp="'第' + (index + 1) + '道问答题'" placement="top" v-for="(ask,index) in examData.askList" :key="ask.id">
                <el-card shadow="never" style="border:0rem;background-color: #F2F6FC;">
                    <template slot="header">
                        <h3 style="margin:0px 0px 20px 0px;display : inline-block" v-html="ask.askContent"></h3>
                    </template>
                    <el-input type="textarea" placeholder="请输入你的答案" v-model="askList[index]" style="width: 100%;height: 100%;"></el-input>
                </el-card>
            </el-timeline-item>
        </el-timeline>


        <el-timeline>
            <el-timeline-item :timestamp="'第' + (index + 1) + '道上机题'"  placement="top" v-for="(upper,index) in examData.upperList" :key="upper.id">
                <el-card shadow="never" style="border:0rem;background-color: mistyrose;">
                    <template slot="header">
                        <el-link style="margin-left: 30px;" type="danger" target="_blank" :href="upper.upperUrl">下载素材</el-link>

                        <el-upload
                                ref="upload"
                                style="float: right;margin-bottom: 10px"
                                name="file"
                                :limit="1"
                                :show-file-list="false"
                                :headers="{'token': token()}"
                                :data="{examId:parentData.id}"
                                action="http://47.97.77.138:56700/student/exam/upload"
                                :on-success="uploadSuccess"
                                :on-exceed="uploadExceed"
                                :on-change="uploadChange"
                                :on-error="uploadError"
                                :file-list="fileList">
                            <el-button size="small" type="primary" :disabled="show">上传上机答案</el-button>
                        </el-upload>
                    </template>
                    <h3 style="margin:0px 0px 20px 0px;display : inline-block" v-html="upper.upperContent"></h3>
                </el-card>
            </el-timeline-item>
        </el-timeline>

    </el-dialog>
</template>
<script>

    import { getToken } from '@/utils/tool';
    import { findExamByRedis,saveTempDataToRedis,echoTempAnswer,saveStudentExam,checkUpperResult } from '@/api/student/student-exam'

    export default {
        name: 'student-exam-show',
        data(){
            return {
                fileList: [],
                show:false,
                fullscreenLoading:false,
                value: false,
                examData:{},
                parentData:{},
                singleAskList:[],
                checkboxAskList:[],
                askList:[],
                timer:'',
                saveTempAnswerTimer:''
            }
        },
        methods:{
            token(){
                return getToken();
            },
            uploadSuccess(response,file,filelist){ //response中有该上机题的id 通过id进行表单数据的修改
                this.$message.success("上传成功");
            },
            uploadError(err,file,fileList){
                this.$message.error(file.name + "文件上传失败");
                this.$refs.upload.uploadFiles = [];
                return false;
            },
            uploadExceed(){
                this.$message.error("上传的文件超出了限定了个数");
                this.$refs.upload.uploadFiles = [];
                return false;
            },
            uploadChange(file,fileList){

                if( !(file.raw.type === 'application/x-zip-compressed')){
                    this.$refs.upload.uploadFiles = [];
                    this.$message.error("只能上传ZIP文件");
                    return false;
                }
                if(file.size / 1024 / 1024 > 200){
                    this.$refs.upload.uploadFiles = [];
                    this.$message.error("上传的文件不能超过200MB");
                    return false;
                }
            },
            handleSubmit(){
                this.$confirm("一旦提交,则不可逆","友情提示",{type:'warning'}).then(()=>{

                    this.saveExam();
                    clearInterval(this.timer);
                });
            },
            saveExam(){
                //不管题型什么样 共同的属性
                let object = {id:this.parentData.id,questionTypeIds:this.parentData.questionTypeIds};
                //试卷中包含的单选题
                if(this.parentData.questionTypeIds.includes("1")){
                    object = Object.assign({singleOptions:this.singleAskList},object);  // Object.assign() => 把2个对象融合在一起  let a = {id:1,name:'张三'} let b = {age:18} ==>  Object.assign(a,b) => {id:1,name:'张三',age:18}
                }

                //试卷中包含多选题
                if(this.parentData.questionTypeIds.includes("2")){
                    //处理多选题数据
                    if(this.checkboxAskList && this.checkboxAskList.length > 0){
                        this.checkboxAskList.forEach(selectionArray=>{
                            if(selectionArray.length > 1){
                                selectionArray = this.splice(selectionArray);
                            }
                        })
                    }
                    object = Object.assign({selectionOptions:this.checkboxAskList.join("@")},object);
                }

                //试卷中包含问答题
                if(this.parentData.questionTypeIds.includes("3")){
                    //处理问答题
                    let arr = [];
                    if(this.askList.length > 0){
                        this.askList.forEach(item=>{
                            if(item == ""){
                                arr.push("暂无答案");
                            }else{
                                arr.push(item);
                            }
                        })
                    }
                    object = Object.assign({askOptions:arr},object);
                }


                this.fullscreenLoading = true;

                saveStudentExam(object).then(res=>{
                    this.$message({
                        type:res.data.success ? 'success':'error',
                        message:res.data.message,
                        center:true
                    });
                    this.value = false;
                    this.fullscreenLoading = false;
                    this.$router.push({name:'student-exam'});
                    this.$parent.getList(this.$parent.params);
                });


            },
            splice(arr){ //1,2,3  [5,1,2,3]
                for(let i = 0 ; i < arr.length ; i ++){
                    if(arr[i] == "5"){
                        arr.splice(i,1); //去掉坐标对应的1个数据
                    }
                }
                return arr;
            }
        },
        watch:{
            value(data){
                if(data){

                    checkUpperResult(this.parentData).then(res=>{
                        if(!res.data.success){
                            this.show = true;
                        }
                    });


                    // 从redis中拿取数据进行展示
                    findExamByRedis(this.parentData).then(res=>{

                        if(res.data.success){
                            this.examData = res.data.data;
                        }


                        //页面渲染单选题答案
                        let singList = res.data.data.singleList;
                        if(singList && singList.length > 0){
                            for(let i = 0 ; i < singList.length ; i ++){
                                this.singleAskList.push("5");
                            }
                        }

                        //页面渲染多选题答案
                        let selectionList = res.data.data.selectionList;
                        if(selectionList && selectionList.length > 0){
                            for(let i = 0 ; i < selectionList.length ; i ++){
                                this.checkboxAskList.push(["5"]);
                            }
                        }

                        //页面渲染完成后，初始化问答题答案
                        let askList = res.data.data.askList;
                        if(askList && askList.length > 0){
                            for(let i = 0; i < askList.length; i++){
                                this.askList.push("");
                            }
                        }

                        //临时保存
                        this.timer = setInterval(()=>{

                            //处理多选题数据
                            if(this.checkboxAskList && this.checkboxAskList.length > 0){
                                this.checkboxAskList.forEach(selectionArray=>{ //[[1,2,3,4],[5],[1,2,3]]
                                    if(selectionArray.length > 1){
                                        selectionArray = this.splice(selectionArray);
                                    }
                                })
                            }

                            //处理问答题
                            let arr = [];
                            if(this.askList.length > 0){
                                this.askList.forEach(item=>{
                                    if(item == ""){
                                        arr.push("暂无答案");
                                    }else{
                                        arr.push(item);
                                    }
                                })
                            }

                            //处理要保存到redis中的临时答案
                            let data = {id:this.parentData.id,singleOptions:this.singleAskList.join(","),selectionOptions:this.checkboxAskList.join("@"),askOptions:arr.join("!&")};


                            //2.进行临时存储
                            saveTempDataToRedis(data).then(res=>{
                                if(!res.data.success){ //强制交卷 :  res.data.success == false
                                    this.saveExam();
                                    clearInterval(this.timer);
                                }
                            })
                        },1000 * 3);


                        //数据回显
                        echoTempAnswer({id:this.parentData.id}).then(res=>{
                            if(res.data.success){
                                if(res.data && res.data.data){
                                    //5,3,5,5,5#5@5@5@5@5#sdadad$&大声道撒大所多
                                    let array = res.data.data.split("#");

                                    //回显单选题
                                    if(array[0]){
                                        this.singleAskList = array[0].split(",");
                                    }


                                    //回显多选题
                                    // 1,2,3 @ 5 @ 1,4   [1,2,3 5 1,4] => [[1,2,3],[5],[1,4]]
                                    if(array[1]){
                                        let arr = [];
                                        array[1].split("@").forEach(item=>{
                                            arr.push(item.split(","));
                                        });
                                        this.checkboxAskList = arr;
                                    }


                                    //回显问答题
                                    if(array[2]){
                                        let arr = [];
                                        array[2].split("!&").forEach(item=>{
                                            arr.push(item);
                                        });
                                        this.askList = arr;
                                    }
                                }
                            }
                        })
                    })

                }
            }
        }
    }
</script>
<style scoped>

</style>